package br.com.bankai.koby.presentation.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.bankai.koby.presentation.util.SessionUtil;
import br.com.bankai.koby.repository.entity.Endereco;
import br.com.bankai.koby.repository.entity.Estado;
import br.com.bankai.koby.repository.entity.Pessoa;
import br.com.bankai.koby.service.impl.EstadoService;
import br.com.graflogic.utilities.cep.CEPClient;
import br.com.graflogic.utilities.cep.exception.CEPNotFoundException;
import br.com.graflogic.utilities.cep.exception.InvalidCEPException;
import br.com.graflogic.utilities.presentationutil.controller.CrudBaseController;

/**
 * 
 * @author Leonardo
 *
 * @param <T>
 * @param <E>
 */
public abstract class PessoaBaseController<T, E> extends CrudBaseController<T, E> implements InitializingBean {

	private static final long serialVersionUID = 5973433486254612550L;

	@Autowired
	private EstadoService estadoService;

	private CEPClient cepClient;

	private List<Estado> estados;

	@Override
	public void afterPropertiesSet() throws Exception {
		cepClient = new CEPClient();

		estados = estadoService.searchAll();
	}

	public Endereco findCep(String cep) {
		Endereco enderecoConsulta = new Endereco();
		if (StringUtils.isNotEmpty(cep)) {
			try {
				br.com.graflogic.utilities.cep.model.Endereco retorno = cepClient.consulta(cep);

				enderecoConsulta.setBairro(retorno.getBairro());
				enderecoConsulta.setCidade(retorno.getCidade());
				enderecoConsulta.setLogradouro(retorno.getLogradouro());
				enderecoConsulta.setEstado(retorno.getUf());
				enderecoConsulta.setCep(cep);
			} catch (CEPNotFoundException e) {
				returnWarnMessage("CEP não encontrado", null, null);
			} catch (InvalidCEPException e) {
				returnWarnMessage("CEP inválido", null, null);
			} catch (Throwable t) {
				returnFatalMessage("Erro ao consultar CEP, contate o administrador", null, t);
			}
		}

		return enderecoConsulta;
	}

	public void beforeSave(Pessoa entity) {
		if (isEditing()) {
			entity.setIdUsuarioAlteracao(SessionUtil.getAuthenticatedUsuario().getId());
		} else {
			entity.setIdUsuarioCadastro(SessionUtil.getAuthenticatedUsuario().getId());
		}
	}

	// Getters e Setters
	public List<Estado> getEstados() {
		return estados;
	}
}